const { promisify } = require("util");
const jwt = require("jsonwebtoken");
const sign = promisify(jwt.sign);
const verify = promisify(jwt.verify);
const helper = require("../helper/helper");
const { jwtSecret } = require("../config");
//创建token
module.exports = {
  async createToken(data) {
    const { username, id, _id } = data;
    const token = await sign({ username, id, _id }, jwtSecret, {
      expiresIn: 3600 * 24,
    });
    return token;
  },
  //验证token
  verifyToken(required = true) {
    return async function (req, res, next) {
      const beararToken = req.headers?.authorization;
      const token = beararToken?.split(" ")?.[1];
      if (token) {
        try {
          const info = await verify(token, jwtSecret);
          req.info = info;
          next();
        } catch (error) {
          return helper.errorMessage({
            res,
            errCode: "UserLoginExpiredError",
            error,
          });
        }
      } else if (required) {
        return helper.errorMessage({ res, errCode: "UserNotLoginError" });
      } else {
        next();
      }
    };
  },
};
